﻿//
//  WeatherViewController.cpp
//  Weather
//
//  Created by 朱建 31990839@qq.com on 16-08-18.
//  Copyright (c) 2014 http://www.9miao.com All rights reserved.

#include "WeatherViewController.h"


WeatherViewController::WeatherViewController()
	:m_pWeatherView(NULL)
{
	std::string fullPath = crossapp_format_string("%sweather_default_city.db", CCFileUtils::sharedFileUtils()->getWritablePath().c_str());
	localStorageInit(fullPath.c_str());

	m_cszXinQiVect.push_back(UTF8("星期一"));
	m_cszXinQiVect.push_back(UTF8("星期二"));
	m_cszXinQiVect.push_back(UTF8("星期三"));
	m_cszXinQiVect.push_back(UTF8("星期四"));
	m_cszXinQiVect.push_back(UTF8("星期五"));
	m_cszXinQiVect.push_back(UTF8("星期六"));
	m_cszXinQiVect.push_back(UTF8("星期日"));
}

WeatherViewController::~WeatherViewController()
{
	localStorageFree();
}

void WeatherViewController::viewDidLoad()
{
	m_pWeatherView = CWeatherView::create();
	m_pWeatherView->setLayout(DLayoutFill);
	m_pWeatherView->setScrollViewDelegate(this);
	this->getView()->addSubview(m_pWeatherView);

	CAButton* switchBtn = CAButton::createWithLayout(DLayout(DHorizontalLayout_R_W(20, 48), DVerticalLayout_T_H(20, 48)), CAButtonTypeRoundedRect);
	switchBtn->setBackGroundViewForState(CAControlStateAll, CAImageView::createWithImage(CAImage::create("r/sw.png")));
	switchBtn->addTarget(this, CAControl_selector(WeatherViewController::onButtonSwitchCity), CAControlEventTouchUpInSide);
	this->getView()->addSubview(switchBtn);
	getWeatherDatas();
}

void WeatherViewController::viewDidUnload()
{
}

void WeatherViewController::viewDidAppear()
{
	getNavigationController()->setNavigationBarHidden(true, false);
	m_pWeatherView->setWeatherDetailFirstResponder(true);
	CAApplication::getApplication()->getKeypadDispatcher()->addDelegate(this);
	getWeatherDatas();
}

void WeatherViewController::viewDidDisappear()
{
	CAApplication::getApplication()->getKeypadDispatcher()->removeDelegate(this);
	m_pWeatherView->setWeatherDetailFirstResponder(false);
}

void WeatherViewController::keyBackClicked()
{
	RootWindow::getInstance()->keyBackClicked();
}

void WeatherViewController::scrollViewHeaderBeginRefreshing(CAScrollView* view)
{
	getWeatherDatas();
}

void WeatherViewController::onButtonSwitchCity(CAControl* target, CCPoint point)
{
	RootWindow::getInstance()->EnterToSwitchCityController();
}

void WeatherViewController::getCurrentCity()
{
	std::map<std::string, std::string> key_value;
	key_value["key"] = gaode_reg_key;
	CommonHttpManager::getInstance()->send_get(get_default_city_url, key_value, this, CommonHttpJson_selector(WeatherViewController::onGetCityRetFinished));
}

void WeatherViewController::getBaseWeather(const std::string& szCity, bool v)
{
	std::map<std::string, std::string> key_value;
	key_value["key"] = gaode_reg_key;
	key_value["city"] = szCity;
	key_value["output"] = "json";
	key_value["extensions"] = v ? "base" : "all";
	CommonHttpManager::getInstance()->send_get(get_weather_url, key_value, this, CommonHttpJson_selector(WeatherViewController::onGetWeatherRetFinished));
}

void WeatherViewController::getWeatherDatas()
{
	std::string szName = RootWindow::getInstance()->getCurCityName();
	if (szName.empty())
	{
		getCurrentCity();
	}
	else
	{
		getBaseWeather(szName, true);
	}
}

void WeatherViewController::onGetCityRetFinished(const HttpResponseStatus& status, const CSJson::Value& json)
{
	if (status != HttpResponseSucceed)
	{
		CAAlertView::createWithText(UTF8("错误"), UTF8("网络异常、请稍候再试!"), UTF8("确定"), NULL)->show();
		return;
	}
	getBaseWeather(json["city"].asCString(), true);
}

void WeatherViewController::onGetWeatherRetFinished(const HttpResponseStatus& status, const CSJson::Value& json)
{
	if (status != HttpResponseSucceed)
	{
		CAAlertView::createWithText(UTF8("错误"), UTF8("网络异常、请稍候再试!"), UTF8("确定"), NULL)->show();
		return;
	}

	if (json.isMember("lives"))
	{
		CSJson::Value v = json["lives"][0];
		m_wData.szCityName = v["city"].asCString();
		m_wData.szWeather = v["weather"].asCString();
		m_wData.szTemperature = v["temperature"].asCString();
		m_wData.szWindpower = v["windpower"].asCString();
		m_wData.szWinddirection = v["winddirection"].asCString();
		m_wData.szHumidity = v["humidity"].asCString();
		getBaseWeather(m_wData.szCityName, false);
	}

	if (json.isMember("forecasts"))
	{
		m_wData.vDayWeathers.clear();
		CSJson::Value v = json["forecasts"][0]["casts"];
		for (int i = 0; i < v.size(); i++)
		{
			CSJson::Value vv = v[i];

			if (i==0)
			{
				m_wData.szTodayDate = vv["date"].asCString();
				m_wData.szTodayTemperature = crossapp_format_string(UTF8("%s°  %s°"), vv["nighttemp"].asCString(), vv["daytemp"].asCString());
			}
			WeatherDayData d;
			d.szWeek = m_cszXinQiVect[atoi(vv["week"].asCString()) - 1];
			d.szDayweather = vv["dayweather"].asCString();
			d.szDayTemperature = crossapp_format_string(UTF8("%s°  %s°"), vv["nighttemp"].asCString(), vv["daytemp"].asCString());
			m_wData.vDayWeathers.push_back(d);
		}
		m_pWeatherView->setDatas(m_wData);
		m_pWeatherView->endHeaderRefresh();
		m_pWeatherView->setContentOffset(DPoint(0, 0), true);
	}
}
